package ks.app.smartDic;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import android.view.KeyEvent;
import android.view.View.OnKeyListener;

public class tabView extends Activity implements OnClickListener {

	private static final int DIALOG_WORD = 1;

	private static final int MODE_DEFINITION = 1;
	private static final int MODE_WORD = 2;
	private static final int MODE_ARTICLE = 3;
	private static final int MODE_EXAMPLE = 4;
	private static final int MODE_SYNONYM = 5;

	ImageButton btnListenNAVER;
	ImageButton btnDefiniton;
	ImageButton btnWord;
	ImageButton btnArticle;
	ImageButton btnExample;
	ImageButton btnSynonum;
	ImageButton btnMemo;
	ImageButton btnVoice;

	AutoCompleteTextForNaverDic editSearchForTab;

	ListView lv;
	TextView contentList;

	String query;

	String sortOfDictionary;

	GoogleAnalyticsTracker tracker;

	Context context;
	SharedPreferences sp;
	Boolean PrefSuperCacheing;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();

		context = this;

		sortOfDictionary = intent
				.getStringExtra(getString(R.string.SORT_OF_DICTIONARY));
		query = intent.getStringExtra("query");

		if (sortOfDictionary.compareTo(getString(R.string.KOREAN_TO_KOREAN)) == 0)
			setContentView(R.layout.tabforkoreandic);
		else
			setContentView(R.layout.tab);

		contentList = (TextView) findViewById(R.id.contentList);
		contentList.setTextColor(Color.BLACK);

		sp = getSharedPreferences("PrefSmartDic", 0);
		PrefSuperCacheing = sp.getBoolean("PrefSuperCacheing", true);

		goSearch();

		editSearchForTab = (AutoCompleteTextForNaverDic) findViewById(R.id.editSearchForTab);
		editSearchForTab
				.setURL("http://ac.endic.naver.com/ac?_callback=&q_enc=utf-8&st=1100&r_format=json&r_enc=utf-8&r_lt=1000&r_unicode=0&r_escape=1&q=");
		editSearchForTab.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN
						&& keyCode == KeyEvent.KEYCODE_ENTER) {

					query = TextBoxValidator.removeReturn(editSearchForTab
							.getText().toString());
					if (editSearchForTab.getText().length() == 0) {
						Toast.makeText(getApplicationContext(),
								"검색어를 입력해 주세요.", Toast.LENGTH_SHORT).show();
						return false;
					}
					editSearchForTab.setText(null);
					goSearch();

				}
				return false;
			}
		});

		btnVoice = (ImageButton) findViewById(R.id.btnVoice);
		btnVoice.setOnClickListener(this);
		btnListenNAVER = (ImageButton) findViewById(R.id.btn_ttsNAVER);
		btnListenNAVER.setOnClickListener(this);
		btnMemo = (ImageButton) findViewById(R.id.btnMemo);
		btnMemo.setOnClickListener(this);

		btnDefiniton = (ImageButton) findViewById(R.id.btnDefiniton);
		btnDefiniton.setOnClickListener(this);
		btnWord = (ImageButton) findViewById(R.id.btnWord);
		btnWord.setOnClickListener(this);
		btnArticle = (ImageButton) findViewById(R.id.btnArticle);
		btnArticle.setOnClickListener(this);
		btnExample = (ImageButton) findViewById(R.id.btnExample);
		btnExample.setOnClickListener(this);
		btnSynonum = (ImageButton) findViewById(R.id.btnSynonum);
		btnSynonum.setOnClickListener(this);

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start("UA-22873894-1", 20, this);
		tracker.trackPageView("/tabview/" + sortOfDictionary);
		tracker.dispatch();

	}

	public void onClick(View v) {

		if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_KOREAN)) == 0) {
			backgroundEngKor dbWord = new backgroundEngKor();
			if (v == btnVoice) {

			} else if (v == btnListenNAVER) {
				goTab();
			} else if (v == btnMemo) {

				// DBHandler dbHandler = new DBHandler();
				// dbHandler.execute(null);

			} else if (v == btnDefiniton) {
				goSearch();
			} else if (v == btnWord) {
				dbWord.execute(MODE_WORD);
			} else if (v == btnArticle) {
				dbWord.execute(MODE_ARTICLE);
			} else if (v == btnExample) {
				dbWord.execute(MODE_EXAMPLE);
			} else if (v == btnSynonum) {
				dbWord.execute(MODE_SYNONYM);
			}
		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_ENG)) == 0) {
			backgroundEngKor dbWord = new backgroundEngKor();

			if (v == btnVoice) {
				Toast.makeText(getApplicationContext(), "다음 버전에서 지원 예정입니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnListenNAVER) {
				goTab();
			} else if (v == btnMemo) {
				Toast.makeText(getApplicationContext(), "다음 버전에서 지원 예정입니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnDefiniton) {
				goSearch();
			} else if (v == btnWord) {
				dbWord.execute(MODE_WORD);
			} else if (v == btnArticle) {
				dbWord.execute(MODE_ARTICLE);
			} else if (v == btnExample) {
				dbWord.execute(MODE_EXAMPLE);
			} else if (v == btnSynonum) {
				Toast.makeText(getApplicationContext(),
						"한영사전에는 유의어/반의어가 없습니다.", Toast.LENGTH_SHORT).show();
			}

		} else if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_ENG)) == 0) {

			if (v == btnVoice) {
				Toast.makeText(getApplicationContext(), "다음 버전에서 지원 예정입니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnListenNAVER) {
				goTab();
			} else if (v == btnMemo) {
				Toast.makeText(getApplicationContext(), "다음 버전에서 지원 예정입니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnDefiniton) {
				goSearch();
			} else if (v == btnWord) {
				backgroundOnlyEng db = new backgroundOnlyEng();
				db.execute(MODE_WORD);
			} else if (v == btnArticle) {
				Toast.makeText(getApplicationContext(), "영영사전에서 지원하지 않습니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnExample) {
				Toast.makeText(getApplicationContext(), "영영사전에서 지원하지 않습니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnSynonum) {
				Toast.makeText(getApplicationContext(), "영영사전에서 지원하지 않습니다.",
						Toast.LENGTH_SHORT).show();
			}

		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_KOREAN)) == 0) {
			backgroundOnlyKor dbKor = new backgroundOnlyKor();
			if (v == btnVoice) {
				Toast.makeText(getApplicationContext(), "다음 버전에서 지원 예정입니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnListenNAVER) {
				Toast.makeText(getApplicationContext(),
						"국어 사전은 발음듣기가 \n지원되지 않습니다.", Toast.LENGTH_SHORT).show();
			} else if (v == btnMemo) {
				Toast.makeText(getApplicationContext(), "다음 버전에서 지원 예정입니다.",
						Toast.LENGTH_SHORT).show();
			} else if (v == btnDefiniton) {
				goSearch();
			} else if (v == btnWord) {
				dbKor.execute(MODE_WORD);
			} else if (v == btnArticle) {
				dbKor.execute(MODE_ARTICLE);
			} else if (v == btnExample) {
				dbKor.execute(MODE_EXAMPLE);
			} else if (v == btnSynonum) {
				dbKor.execute(MODE_SYNONYM);
			}
		}

	}

	protected void onResume() {

		super.onResume();

	}

	private void goSearch() {

		NaverURLManager.setQuery(query);
		NaverURLManager.setSortOfDictionary(sortOfDictionary);

		if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_KOREAN)) == 0) {
			backgroundEngKor goSearch = new backgroundEngKor();
			goSearch.execute(MODE_DEFINITION);
		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_ENG)) == 0) {
			backgroundEngKor goSearch = new backgroundEngKor();
			goSearch.execute(MODE_DEFINITION);
		} else if (sortOfDictionary.compareTo(getString(R.string.ENG_TO_ENG)) == 0) {
			backgroundOnlyEng db = new backgroundOnlyEng();
			db.execute(MODE_DEFINITION);
		} else if (sortOfDictionary
				.compareTo(getString(R.string.KOREAN_TO_KOREAN)) == 0) {
			backgroundOnlyKor db = new backgroundOnlyKor();
			db.execute(MODE_DEFINITION);
		}

	}

	private class backgroundEngKor extends AsyncTask<Integer, String, String> {

		String sb;
		Boolean superCached;

		backgroundEngKor() {
			sb = "";
			superCached = false;
		}

		protected String doInBackground(Integer... param) {

			ksLog.d("param", param[0]);

			SmartDatabase sDB = new SmartDatabase(getApplicationContext());
			String encodedQuery = "";
			if (PrefSuperCacheing) {

				sDB.open();

				try {
					encodedQuery = URLEncoder.encode(query, "UTF-8");
				} catch (Exception e) {
					ksLog.d("encoding exception");
				}

				try {

					ksLog.d("1", sortOfDictionary);
					ksLog.d("2", param[0]);
					ksLog.d("3", encodedQuery);

					Cursor result = sDB.selectWord(sortOfDictionary, param[0],
							encodedQuery);

					if (!result.isNull(0)) {
						sb = result.getString(0);
						superCached = true;
					}

					result.close();
				} catch (Exception e) {
					ksLog.d("record exception", e.getMessage());

				}
			}

			if (sb.length() == 0) {

				httpClient hp = new httpClient();
				jerichoParser jp = new jerichoParser(query);

				InputStream http_data = hp.post(NaverURLManager
						.getUrl(param[0]));

				if (param[0] == MODE_DEFINITION) {
					sb = jp.parseDefinition(http_data);
				} else if (param[0] == MODE_WORD || param[0] == MODE_ARTICLE) {
					sb = jp.parseWord(http_data);
				} else if (param[0] == MODE_EXAMPLE) {
					sb = jp.parseExample(http_data);
				} else if (param[0] == MODE_SYNONYM) {
					sb = jp.parseSynonum(http_data);
				}

				if (sb.length() == 0) {

					List<NameValuePair> myList = new ArrayList<NameValuePair>();
					myList.add(new BasicNameValuePair("query", query));
					myList.add(new BasicNameValuePair("sort", sortOfDictionary));
					myList.add(new BasicNameValuePair("mode", String
							.valueOf(param[0])));
					myList.add(new BasicNameValuePair("versionCode", String
							.valueOf(getVersionCode())));
					hp.postEUCKR("http://hydra01.woweb.net/cloud/insert.php",
							myList);

					tracker.setCustomVar(1, "WORD_FAIL", "<" + sortOfDictionary
							+ "_" + TextBoxValidator.removeReturn(query) + "_"
							+ param[0] + ">", 1);
					tracker.dispatch();
				} else {

					if (PrefSuperCacheing) {
						ksLog.d("insert");
						sDB.insertWord(sortOfDictionary, param[0],
								encodedQuery, sb.toString());
					}

				}
			}

			sDB.close();

			return null;
		}

		@Override
		protected void onPreExecute() {

			showDialog(DIALOG_WORD);

		}

		protected void onProgressUpdate(String... values) {

		}

		protected void onPostExecute(String result) {

			try {
				removeDialog(DIALOG_WORD);

				if (sb.length() == 0)
					contentList.setText(TextBoxValidator.removeReturn(query)
							+ "에 해당하는 검색 결과가 없습니다.");
				else {
					contentList.setText(Html.fromHtml(sb));

					if (superCached)
						Toast.makeText(getApplicationContext(), "슈퍼 캐싱 사용",
								Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				tracker.setCustomVar(1, "EXCEPTION_KOR_TO_ENG_ON_POST",
						e.getMessage(), 1);
				tracker.dispatch();
			}

		}

	}

	private class backgroundOnlyEng extends AsyncTask<Integer, String, String> {

		String sb;

		Boolean superCached;

		backgroundOnlyEng() {
			sb = "";
			superCached = false;
		}

		protected String doInBackground(Integer... param) {

			SmartDatabase sDB = new SmartDatabase(getApplicationContext());
			String encodedQuery = "";
			if (PrefSuperCacheing) {
				sDB.open();

				try {
					encodedQuery = URLEncoder.encode(query, "UTF-8");
				} catch (Exception e) {
					ksLog.d("encoding exception");
				}

				try {
					Cursor result = sDB.selectWord(sortOfDictionary, param[0],
							encodedQuery);

					if (!result.isNull(0)) {
						sb = result.getString(0);
						superCached = true;
					}

					result.close();
				} catch (Exception e) {
					ksLog.d("record exception", e.getMessage());

				}
			}
			if (sb.length() == 0) {
				httpClient hp = new httpClient();
				jerichoParser jp = new jerichoParser(query);
				InputStream http_data = hp.post(NaverURLManager
						.getUrl(param[0]));

				if (param[0] == MODE_DEFINITION) {
					sb = jp.parseOnlyEngDefinition(http_data);
				} else if (param[0] == MODE_WORD) {
					sb = jp.parseOnlyEngWord(http_data);
				}

				if (sb.length() == 0) {

					List<NameValuePair> myList = new ArrayList<NameValuePair>();
					myList.add(new BasicNameValuePair("query", query));
					myList.add(new BasicNameValuePair("sort", sortOfDictionary));
					myList.add(new BasicNameValuePair("mode", String
							.valueOf(param[0])));
					myList.add(new BasicNameValuePair("versionCode", String
							.valueOf(getVersionCode())));
					hp.postEUCKR("http://hydra01.woweb.net/cloud/insert.php",
							myList);

					tracker.setCustomVar(1, "WORD_FAIL", "<" + sortOfDictionary
							+ "_" + TextBoxValidator.removeReturn(query) + "_"
							+ param[0] + ">", 1);
					tracker.dispatch();
				} else {

					if (PrefSuperCacheing) {
						ksLog.d("insert");
						sDB.insertWord(sortOfDictionary, param[0],
								encodedQuery, sb.toString());
					}

				}
			}

			return null;
		}

		@Override
		protected void onPreExecute() {

			showDialog(DIALOG_WORD);

		}

		protected void onProgressUpdate(String... values) {

		}

		protected void onPostExecute(String result) {

			try {
				removeDialog(DIALOG_WORD);

				if (sb.length() == 0)
					contentList.setText(TextBoxValidator.removeReturn(query)
							+ "에 해당하는 검색 결과가 없습니다.");
				else {
					contentList.setText(Html.fromHtml(sb));
					if (superCached)
						Toast.makeText(getApplicationContext(), "슈퍼 캐싱 사용",
								Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				tracker.setCustomVar(1, "EXCEPTION_ENG_TO_ENG_ON_POST",
						e.getMessage(), 1);
				tracker.dispatch();
			}

		}

	}

	private class backgroundOnlyKor extends AsyncTask<Integer, String, String> {

		String sb;
		Boolean superCached;

		backgroundOnlyKor() {

			sb = "";
			superCached = false;
		}

		protected String doInBackground(Integer... param) {

			SmartDatabase sDB = new SmartDatabase(getApplicationContext());
			String encodedQuery = "";
			if (PrefSuperCacheing) {
				sDB.open();

				try {
					encodedQuery = URLEncoder.encode(query, "UTF-8");
				} catch (Exception e) {
					ksLog.d("encoding exception");
				}

				try {
					Cursor result = sDB.selectWord(sortOfDictionary, param[0],
							encodedQuery);

					if (!result.isNull(0)) {
						sb = result.getString(0);
						superCached = true;
					}

					result.close();
				} catch (Exception e) {
					ksLog.d("record exception", e.getMessage());

				}
			}

			if (sb.length() == 0) {
				httpClient hp = new httpClient();
				jerichoParser jp = new jerichoParser(query);
				InputStream http_data = hp.post(NaverURLManager
						.getUrl(param[0]));

				if (param[0] == MODE_DEFINITION) {
					sb = jp.parseKorDefinition(http_data, "단어");
				} else if (param[0] == MODE_WORD) {
					sb = jp.parseKorDefinition(http_data, "속담/관용구");
				} else if (param[0] == MODE_ARTICLE) {
					sb = jp.parseKorDefinition(http_data, "본문");
				} else if (param[0] == MODE_EXAMPLE) {
					sb = jp.parseKorDefinition(http_data, "예문");
				} else if (param[0] == MODE_SYNONYM) {
					sb = jp.parseKorDefinition(http_data, "맞춤법/표기법");
				}

				if (sb.length() == 0) {

					List<NameValuePair> myList = new ArrayList<NameValuePair>();
					myList.add(new BasicNameValuePair("query", query));
					myList.add(new BasicNameValuePair("sort", sortOfDictionary));
					myList.add(new BasicNameValuePair("mode", String
							.valueOf(param[0])));
					myList.add(new BasicNameValuePair("versionCode", String
							.valueOf(getVersionCode())));
					hp.postEUCKR("http://hydra01.woweb.net/cloud/insert.php",
							myList);

					tracker.setCustomVar(1, "WORD_FAIL", "<" + sortOfDictionary
							+ "_" + TextBoxValidator.removeReturn(query) + "_"
							+ param[0] + ">", 1);
					tracker.dispatch();
				} else {

					if (PrefSuperCacheing) {
						ksLog.d("insert");
						sDB.insertWord(sortOfDictionary, param[0],
								encodedQuery, sb.toString());
					}

				}
			}

			return null;
		}

		@Override
		protected void onPreExecute() {

			showDialog(DIALOG_WORD);

		}

		protected void onProgressUpdate(String... values) {

		}

		protected void onPostExecute(String result) {

			try {
				removeDialog(DIALOG_WORD);

				if (sb.length() == 0)
					contentList.setText(TextBoxValidator.removeReturn(query)
							+ "에 해당하는 검색 결과가 없습니다.");
				else {
					contentList.setText(Html.fromHtml(sb));
					if (superCached)
						Toast.makeText(getApplicationContext(), "슈퍼 캐싱 사용",
								Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				ksLog.d("kor exception", e.getMessage());
			}

		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_WORD: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("단어 검색 중...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}

		}
		return null;
	}

	void goTab() {
		Intent goTabIntent = new Intent(getApplicationContext(), TTS.class);
		goTabIntent.putExtra("query", query);
		goTabIntent.putExtra(getString(R.string.SORT_OF_DICTIONARY),
				sortOfDictionary);
		startActivity(goTabIntent);
	}

	int getVersionCode() {
		int versionCode = -1;

		try {
			versionCode = getPackageManager().getPackageInfo(getPackageName(),
					0).versionCode;
		} catch (Exception e) {
			ksLog.d("versionException", e.getMessage());
		}

		return versionCode;
	}

	Boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm.getActiveNetworkInfo().isAvailable();
	}

	private class DBHandler extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... arg0) {

			SmartDatabase sDB = new SmartDatabase(getApplicationContext());
			String encodedQuery = "";

			sDB.open();

			try {
				encodedQuery = URLEncoder.encode(query, "UTF-8");
			} catch (Exception e) {
				ksLog.d("encoding exception");
			}

			try {

				String result = sDB.updateWord(encodedQuery, sortOfDictionary);

				sDB.close();
			} catch (Exception e) {
				ksLog.d("record exception", e.getMessage());

			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {

			Toast.makeText(getApplicationContext(), "단어장에 저장되었습니다.",
					Toast.LENGTH_SHORT).show();
			super.onPostExecute(result);
		}

	};

}
